<template>
  <div class="parkingArea-list">
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="Home" :replace="true">首页</el-breadcrumb-item>
        <el-breadcrumb-item>车位信息列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-form :inline="true" :model="parkingAreaQueryForm" ref="parkingAreaQueryFormRef" :rules="rules">
      <el-form-item label="车位号" prop="areaNumber">
        <el-input v-model="parkingAreaQueryForm.areaNumber" placeholder="请输入车位号" maxlength="32"></el-input>
      </el-form-item>
      <el-form-item label="楼栋名称" prop="buildingName">
        <el-input v-model="parkingAreaQueryForm.buildingName" placeholder="请选择楼栋名称" readonly="readonly">
          <template #suffix>
            <el-icon @click="findBuilding"><Search/></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="所在楼层" prop="floorNumber">
        <el-input v-model="parkingAreaQueryForm.floorNumber" placeholder="请输入所在楼层" maxlength="32"></el-input>
      </el-form-item>
      <el-form-item label="单元房号" prop="residentRoomNumber">
        <el-input v-model="parkingAreaQueryForm.residentRoomNumber" placeholder="请选择单元房号" readonly="readonly">
          <template #suffix>
            <el-icon @click="findRoom"><Search/></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="车牌" prop="licensePlate">
        <el-input v-model="parkingAreaQueryForm.licensePlate" placeholder="请输入车牌" maxlength="32"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="parkingAreaQueryForm.status" placeholder="请选择状态" class="select-custom">
          <el-option label="临停" :value="30"></el-option>
          <el-option label="业主" :value="10"></el-option>
          <el-option label="月租" :value="20"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onAdd">新增</el-button>
        <el-button type="primary" @click="onExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="state.tableData"
      border
      v-loading="state.loading"
      size="small"
      header-cell-class-name="table-header-cell-font"
      cell-class-name="table-cell-font">
      <el-table-column prop="areaNumber" label="车位号"></el-table-column>
      <el-table-column prop="buildingName" label="楼栋名称"></el-table-column>
      <el-table-column prop="floorNumber" label="所在楼层"></el-table-column>
      <el-table-column prop="residentRoomNumber" label="单元房号"></el-table-column>
      <el-table-column prop="licensePlate" label="车牌"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template v-slot="{ row }">
          <div v-if="row.status === 30">临停</div>
          <div v-if="row.status === 10">业主</div>
          <div v-if="row.status === 20">月租</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template v-slot="{ row }">
          <el-button @click.native.prevent="editRow(row.id)" type="primary">编辑</el-button>
          <el-button @click.native.prevent="delRow(row.id)" type="danger" plain>删除</el-button>
          <el-button @click.native.prevent="detailRow(row.id)" type="primary" plain>详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination
        @current-change="changePage"
        :current-page="state.currentPage"
        :page-sizes="state.pageSizes"
        :page-size="state.pageSize"
        background
        layout="total, prev, pager, next, jumper"
        :total="state.total">
      </el-pagination>
    </div>
    <el-dialog v-model="buildingSelectorVisible" v-if="buildingSelectorVisible" title="楼栋信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <building-selector @building-selected-event="handleBuildingSelectedEvent">
      </building-selector>
    </el-dialog>
    <el-dialog v-model="roomSelectorVisible" v-if="roomSelectorVisible" title="单元信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <room-selector @room-selected-event="handleRoomSelectedEvent">
      </room-selector>
    </el-dialog>
    <el-dialog v-model="parkingAreaAddVisible" v-if="parkingAreaAddVisible" :title="parkingAreaAddTitle" :top="dialogTop" :width="dialogWidth">
      <parking-area-add :id="selectedParkingAreaId" @close-parking-area-add-event="handleCloseParkingAreaAddEvent" @reset-parking-area-add-event="handleResetParkingAreaAddEvent">
      </parking-area-add>
    </el-dialog>
    <el-dialog v-model="parkingAreaViewVisible" v-if="parkingAreaViewVisible" title="车位信息详情" :top="dialogTop" :width="dialogWidth">
      <parking-area-view :id="selectedParkingAreaId" @close-parking-area-view-event="handleCloseParkingAreaViewEvent">
      </parking-area-view>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, inject, toRefs} from 'vue';
import parkingAreaApi from '@/api/parkingAreaApi'
import type {ParkingAreaQueryForm} from "@/types/req/parkingAreaQueryForm";
import type {ParkingArea} from "@/types/resp/parkingArea";
import {ElMessage, ElMessageBox, type FormInstance} from "element-plus";
import type {Result} from "@/types/result";
import type {Page} from "@/types/page";
import { Search } from '@element-plus/icons-vue';
import BuildingSelector from "@/views/building/BuildingSelector.vue";
import RoomSelector from "@/views/room/RoomSelector.vue";
import ParkingAreaAdd from "@/views/parkingArea/ParkingAreaAdd.vue"
import ParkingAreaView from "@/views/parkingArea/ParkingAreaView.vue"
import { exportToExcel } from '@/composables/exportUtil.ts'
import {getPropertyParkingAreaStatusText} from "@/composables/dictTranslator.ts";

const parkingAreaQueryFormRef = ref<FormInstance | null>(null);
let parkingAreaQueryForm = reactive<ParkingAreaQueryForm>({
  areaNumber: '',
  buildingId: 0,
  buildingName: '',
  floorNumber: '',
  residentRoomId: 0,
  residentRoomNumber: '',
  licensePlate: '',
  status: undefined,
})

const state = reactive({
  loading: false,
  tableData: [] as ParkingArea[], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  pageSizes: [10, 20, 50]
})
const selectedParkingAreaId = ref<number>(0)
const buildingSelectorVisible = ref<boolean>(false)
const roomSelectorVisible = ref<boolean>(false)
const parkingAreaAddVisible = ref<boolean>(false)
const parkingAreaViewVisible = ref<boolean>(false)
const parkingAreaAddTitle = ref<string>('')
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')

const rules = reactive({
});

onMounted(() => {
  onSearch()
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
})

const getPageData = async () => {
  try {
    state.loading = true
    const resp: Result<Page<ParkingArea>> = await parkingAreaApi.find(parkingAreaQueryForm)
    if (resp && resp.code === 1) {
      if (resp.data) {
      const page: Page<ParkingArea> = resp.data
        if (page && page.list.length > 0) {
          state.tableData = page.list
          state.total = page.total
        }
      }
    }
  } catch (e) {
    console.log('获取数据异常', e)
  } finally {
    state.loading = false
  }
}
const onSearch = () => {
  getPageData()
}

const changePage = (val: number) => {
  state.currentPage = val
  getPageData()
}

const onReset = () => {
  if (parkingAreaQueryFormRef.value) {
    parkingAreaQueryFormRef.value.resetFields()
  }
  state.currentPage = 1
  getPageData()
}

const onAdd = () => {
  selectedParkingAreaId.value = 0
  parkingAreaAddVisible.value = true
  parkingAreaAddTitle.value = '车位信息新增'
}
const editRow = (id: number) => {
  selectedParkingAreaId.value = id
  parkingAreaAddVisible.value = true
  parkingAreaAddTitle.value = '车位信息编辑'
}
const delRow = (id: number) => {
  if (!id) {
    return
  }
  ElMessageBox.confirm(
    '确定要删除吗?',
    '删除提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    parkingAreaApi.del(id)
      .then((resp) => {
        if (resp && resp.code === 1) {
          ElMessage.success('删除成功!')
          onSearch()
        } else {
          ElMessage.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
        }
      })
      .catch(error => {
        console.error('操作失败:', error)
      })
  }).catch(() => {})
}
const detailRow = (id:number) => {
  selectedParkingAreaId.value = id
  parkingAreaViewVisible.value = true
}

const findBuilding = () => {
  buildingSelectorVisible.value = true
}

const handleBuildingSelectedEvent = (selectedBuilding: any) => {
  buildingSelectorVisible.value = false
  if (selectedBuilding && 'buildingId' in selectedBuilding && parkingAreaQueryForm.buildingId !== selectedBuilding['buildingId']) {
    parkingAreaQueryForm.buildingId = selectedBuilding['buildingId']
    parkingAreaQueryForm.buildingName = selectedBuilding['buildingName']
  }
}
const findRoom = () => {
  roomSelectorVisible.value = true
}

const handleRoomSelectedEvent = (selectedRoom: any) => {
  roomSelectorVisible.value = false
  if (selectedRoom && 'residentRoomId' in selectedRoom && parkingAreaQueryForm.residentRoomId !== selectedRoom['residentRoomId']) {
    parkingAreaQueryForm.residentRoomId = selectedRoom['residentRoomId']
    parkingAreaQueryForm.residentRoomNumber = selectedRoom['residentRoomNumber']
  }
}

const handleCloseParkingAreaViewEvent = () => {
  parkingAreaViewVisible.value = false
}

const handleResetParkingAreaAddEvent = () => {
  parkingAreaAddTitle.value = '车位信息新增'
}

const handleCloseParkingAreaAddEvent = (params: { search?: boolean } | undefined) => {
  if (params && params.search) {
    onSearch()
  }
  parkingAreaAddVisible.value = false
}

const onExport = () => {
  const headers = ['车位号','楼栋名称','所在楼层','单元房号','车牌','状态']
  parkingAreaApi.find(parkingAreaQueryForm).then(data => {
    if (!data || !data.data || data.data.list.length < 1) {
      ElMessage.error('无数据导出')
      return
    }
    const exportData = []
    for (const d of data.data.list) {
      exportData.push([d.areaNumber,d.buildingName,d.floorNumber,d.residentRoomNumber,d.licensePlate,getPropertyParkingAreaStatusText(d.status)])
    }
    exportToExcel(headers, exportData)
  })
}
</script>

<style lang="scss">
</style>